#include "mensagem.h"
#include "about.h"
#include "selecionararquivo.h"
#include "treeviewdelegate.h"

#include "parser/parser_factory.h"
#include "parser/parser.h"

#include "mainwindow.h"
#include "ui_mainwindow.h"

MainWindow::MainWindow(QWidget *parent) :
    QMainWindow(parent),
    ui(new Ui::MainWindow)
{
    ui->setupUi(this);

    ui->treeView->setItemDelegate(new TreeViewDelegate(ui->treeView));

    ui->comboTipo->setVisible(false);
    ui->lineEdit2->setVisible(false);
    ui->labelEntre->setVisible(false);
}

MainWindow::~MainWindow()
{
    delete ui;
    delete parser;
}

void MainWindow::on_actionSobre_triggered() {
    About *about = new About(this);
    about->show();
}

void MainWindow::on_comboBox_activated(int index) {
    ui->lineEdit->clear();
    ui->lineEdit2->clear();

    setFieldFilter(index);
}

void MainWindow::setFieldFilter(int index) {
    QList<Sensor *> sensores = parser->getSensors();
    Sensor *sensor = sensores.at(index);

    ui->comboTipo->setVisible(false);
    ui->lineEdit2->setVisible(false);
    ui->labelEntre->setVisible(false);

    ui->lineEdit->setInputMask("");

    if (!sensor->getTipo().compare("REAL")) {
        ui->comboTipo->setVisible(true);
    }
    else if (!sensor->getTipo().compare("DATETIME")) {
        ui->lineEdit->setInputMask("##/##/#### ##:##:##");
        ui->lineEdit2->setVisible(true);
        ui->labelEntre->setVisible(true);
    }
}

void MainWindow::on_buttomSearch_clicked() {
    QList<Sensor *> sensores = parser->getSensors();
    Sensor *sensor = sensores.at(ui->comboBox->currentIndex());

    QString campo = ui->lineEdit->text();
    QString compTipo = "=";
    QString query = "";

    if (!sensor->getTipo().compare("REAL")) {
        int tipoIndex = ui->comboTipo->currentIndex();
        if (tipoIndex == 0)
            compTipo = ">";
        else if (tipoIndex == 1)
            compTipo = "<";
    }
    else if (!sensor->getTipo().compare("DATETIME")) {
        QString campo2 = ui->lineEdit2->text();

        QDateTime dateTime = QDateTime::fromString(campo, "dd/MM/yyyy hh:mm:ss");
        QDateTime dateTime2 = QDateTime::fromString(campo2, "dd/MM/yyyy hh:mm:ss");

        if (!dateTime.isValid() || !dateTime2.isValid())
            return;

        campo = "'" + dateTime.toString("yyyy-MM-dd hh:mm:ss") +"'";
        campo2 = "'" + dateTime2.toString("yyyy-MM-dd hh:mm:ss") +"'";

        query = " and " + sensor->getColuna() + "<" + campo2;
        compTipo = ">";
    }
    else {
        campo = "'%" + campo +"%'";
        compTipo = " like ";
    }

    query =  sensor->getColuna()+compTipo+campo + query;
    qDebug() << query;

    makeList(query);
}

void MainWindow::on_actionAbrir_triggered() {
    QString str1=SelecionarArquivo::abrir("Abrir projeto", "Estação (*.txt)");
    if (str1.isEmpty())
       return;

    openParser(str1.toUtf8());
    makeCombo();
    makeList("");

    setFieldFilter(0);
}

void MainWindow::on_actionExportar_triggered() {
    QString str1=SelecionarArquivo::salvar("Salvar projeto",".",  "Estação (*.csv)");
    if (str1.isEmpty())
       return;

    if (str1.lastIndexOf(".csv") == -1)
        str1 = str1+".csv";

    QFile data(str1);
    if (data.open(QFile::WriteOnly | QFile::Truncate)) {
        QTextStream out(&data);

        for(int i=0; i<this->model->columnCount() ;i++) {
            out << model->headerData(i, Qt::Horizontal, Qt::DisplayRole).toString() << ",";
        }

        out << "\n";

        for(int i=0; i<this->model->rowCount() ;i++) {
            for(int j=0; j<this->model->columnCount() ;j++) {
                QStandardItem *item = this->model->item(i, j);
                out << item->data(Qt::DisplayRole).toString() << ",";
            }

            out << "\n";
        }

        data.close();
    }
}

void MainWindow::openParser(QString file) {
    ParserFactory factory;
    parser = factory.select_station(file);
    parser->setFile(file);
    parser->parse();
}

void MainWindow::makeList(QString where) {
    QList<Sensor *> sensores = parser->getSensors();

    model = new QStandardItemModel(0, sensores.length());

    for (int i = 0; i < sensores.size(); ++i) {
        Sensor *sensor = sensores.at(i);

        model->setHeaderData(i, Qt::Horizontal, sensor->getNome());
    }

    ui->treeView->setModel(model);

    QString sql = "select * from Estacao";

    if (where.length() > 0)
        sql+=" where "+where;

    QSqlQuery query(sql);

    if (!query.exec()) {
      Mensagem::erro("Erro", "Erro: " + query.lastError().text());
      return;
    }

    QSqlRecord record=query.record();
    int numCol=record.count();

    while (query.next()) {
      int num=model->rowCount(QModelIndex());
      model->insertRow(num);

      for (int i=0; i<numCol ;i++) {
          Sensor *sensor = sensores.at(i);

          if (!sensor->getTipo().compare("REAL"))
            model->setData(model->index(num, i), query.value(i).toFloat());
          else if (!sensor->getTipo().compare("DATETIME")) {
            QString date = query.value(i).toDateTime().toString("dd/MM/yyyy hh:mm:ss");
            model->setData(model->index(num, i), date);
          }
          else
              model->setData(model->index(num, i), query.value(i).toString());
      }
    }


    for (int i = 0; i < sensores.size(); ++i) {
        if (i == 0)
            ui->treeView->setColumnWidth(0, 180);
        else
            ui->treeView->setColumnWidth(i, 100);
    }

}

void MainWindow::makeCombo() {
    QList<Sensor *> sensores = parser->getSensors();

    ui->comboBox->clear();
    for (int i = 0; i < sensores.size(); ++i) {
        Sensor *sensor = sensores.at(i);

        ui->comboBox->addItem(sensor->getNome());
    }
}
